/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	public static void  invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// 如果有的话，首先调用 BeanDefinitionRegistryPostProcessors.
		// 集合一: 保存已经处理的 BeanFactoryPostProcessor 集合
		Set<String> processedBeans = new HashSet<>();
		// 判断 IOC 容器是不是 BeanDefinitionRegistry 的？
		if (beanFactory instanceof BeanDefinitionRegistry) {
			// 把 IOC 容器强制转为 BeanDefinitionRegistry 类型
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// 集合二: 创建一个普通的 BeanFactoryPostProcessor 的 list 的集合
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			// 集合三: 创建一个 BeanDefinitionRegistryPostProcessor 的 list 的集合
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			/** $$$$ <第一个拓展点> $$$$ */
			// 处理容器硬编码 (new 出来的) 带入的 beanFactoryPostProcessors (一般 size = 0,直接跳过)
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				// 判断是不是 BeanDefinitionRegistryPostProcessor 类型
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					// 调用 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					// 加入到对应 BeanDefinitionRegistryPostProcessor 类型的 list 集合中
					registryProcessors.add(registryProcessor);
				}
				else { // 否则是 BeanFactoryPostProcessor 类型，加入到对应类型的 list 集合中，之后执行
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			// 集合四: 创建一个当前注册的 RegistryProcessors 的集合
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			/** $$$$ <第二个拓展点> $$$$ */
			/** First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. */
			// 从容器中获取 BeanDefinitionRegistryPostProcessor.class 类型的 BeanNames
			// BeanNames = {AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME}
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// 判断 BeanDefinitionRegistryPostProcessor 是不是实现了 PriorityOrdered 接口 (实现了)
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					// 2.getBean() 通过 BeanName 和 class 实例化 BeanDefinitionRegistryPostProcessor
					// 3.将实例化好的 BeanDefinitionRegistryPostProcessor 的对象放入 currentRegistryProcessors 集合
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 添加到已经处理 processedBeans 的集合中
					processedBeans.add(ppName);
				}
			}
			// 进行排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 加入到对应 BeanDefinitionRegistryPostProcessor 类型的 list 集合中
			registryProcessors.addAll(currentRegistryProcessors);
			/**1.非常重要的一个方法: */
			// 调用 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry 方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 将 currentRegistryProcessors 集合清空
			currentRegistryProcessors.clear();

			/** Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. */
			// 去容器中查询是否有 BeanDefinitionRegistryPostProcessor 类型 beanName
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// 如果 BeanDefinitionRegistryPostProcessor 没有被处理过，并且实现了 Ordered 接口
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName); // 添加到已经处理 processedBeans 的集合中
				}
			}
			// 进行排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 加入到对应 BeanDefinitionRegistryPostProcessor 类型的 list 集合中
			registryProcessors.addAll(currentRegistryProcessors);
			/*1.非常重要的一个方法: */
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 将 currentRegistryProcessors 集合清空
			currentRegistryProcessors.clear();

			/** Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. */
			// 调用普通的 BeanDefinitionRegistryPostProcessors 没用实现 PriorityOrdered 和 Ordered 接口
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName); // 添加到已经处理 processedBeans 的集合中
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}

			/** Now, invoke the postProcessBeanFactory callback of all processors handled so far. */
			// 调用上诉实现了也实现了 BeanFactoryPostProcessors 的接口
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);    // 集合三的
			// 执行容器硬编码 (new 出来的) 带入的 beanFactoryPostProcessors
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); // 集合二的
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// 不要在这里初始化FactoryBeans: 我们需要保持所有常规bean未初始化，以便让bean工厂后处理器应用到它们!
		// 去 IOC 容器中获取 BeanFactoryPostProcessor 类型的 beanNames
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// 分离实现了 [PriorityOrdered接口的] [Ordered接口的] [普通的] BeanFactoryPostProcessor
		// 1.实现了 [PriorityOrdered接口的] BeanFactoryPostProcessor 集合
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 2.实现了 [Ordered接口的] BeanFactoryPostProcessor 集合
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 3.什么排序接口也没实现 [普通的] BeanFactoryPostProcessor 集合
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 循环进行分类
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// 跳过 — 已经在上面的第一阶段处理
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		// 调用 PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		// 调用 Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		// 调用普通的 BeanFactoryPostProcessors
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		/* 获取所有 BeanPostProcessor.class 类型的 BeanDefinition 的 beanName */
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		/** 注册BeanPostProcessorChecker，当bean在BeanPostProcessor实例化过程中创建时，
		    即当一个 bean 不能被所有 BeanPostProcessor 处理时，记录一个信息消息. */
		/* 获取 BeanPostProcessor 的总个数 = 成品 + 1 + 半成品 */
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		/* 又注册了一个系统的成品 */
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		/** 分离实现了 PriorityOrdered | Ordered | 其他的 BeanPostProcessors */
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		/* 循环半成品 */
		for (String ppName : postProcessorNames) {
			// 1.如果是 PriorityOrdered.class 类型的
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 创建对应的 BeanPostProcessor
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				// 添加 [成品] 到对应的集合
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			// 2.如果是 Ordered.class 类型的
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				// 添加 [半成品] 到对应的集合
				orderedPostProcessorNames.add(ppName);
			}
			// 3.其他类型的
			else {
				// 添加 [半成品] 到对应的集合
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// (1) 首先，注册实现 PriorityOrdered 的 BeanPostProcessor.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// (2) 接下来，注册实现 Ordered 的 BeanPostProcessors.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String ppName : orderedPostProcessorNames) {
			// 创建对应的 BeanPostProcessor
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			// 添加 [成品] 到对应的集合
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// (3) 现在，注册所有常规 BeanPostProcessor.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String ppName : nonOrderedPostProcessorNames) {
			// 创建对应的 BeanPostProcessor
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			// 添加 [成品] 到对应的集合
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// 最后，重新注册所有 internal BeanPostProcessors.
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);  // -->
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
